{{- define "dex_authenticator_resources" }}
cpu: 10m
memory: 25Mi
{{- end }}

{{- define "redis_resources" }}
cpu: 10m
memory: 25Mi
{{- end }}

{{- $context := . }}
{{- range $crd := $context.Values.userAuthn.internal.dexAuthenticatorCRDs }}
  {{- if $context.Values.global.enabledModules | has "vertical-pod-autoscaler-crd" }}
---
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: {{ $crd.name }}-dex-authenticator
  namespace: {{ $crd.namespace }}
  {{- include "helm_lib_module_labels" (list $context (dict "app" "dex-authenticator")) | nindent 2 }}
spec:
  targetRef:
    apiVersion: "apps/v1"
    kind: Deployment
    name: {{ $crd.name }}-dex-authenticator
  updatePolicy:
    updateMode: "Auto"
  resourcePolicy:
    containerPolicies:
    - containerName: "dex-authenticator"
      minAllowed:
        {{- include "dex_authenticator_resources" . | nindent 8 }}
      maxAllowed:
        cpu: 20m
        memory: 50Mi
    - containerName: "redis"
      minAllowed:
        {{- include "redis_resources" . | nindent 8 }}
      maxAllowed:
        cpu: 20m
        memory: 50Mi
  {{- end }}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: {{ $crd.name }}-dex-authenticator
  namespace: {{ $crd.namespace }}
  {{- include "helm_lib_module_labels" (list $context (dict "app" "dex-authenticator")) | nindent 2 }}
spec:
  minAvailable: {{ include "helm_lib_is_ha_to_value" (list $context 1 0) }}
  selector:
    matchLabels:
      app: dex-authenticator
      name: {{ $crd.name }}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ $crd.name }}-dex-authenticator
  namespace: {{ $crd.namespace }}
  {{- include "helm_lib_module_labels" (list $context (dict "app" "dex-authenticator")) | nindent 2 }}
spec:
  replicas: {{ include "helm_lib_is_ha_to_value" (list $context 2 1) }}
  revisionHistoryLimit: 2
  strategy:
    type: RollingUpdate
    {{- if (include "helm_lib_ha_enabled" $context) }}
    rollingUpdate:
      maxSurge: 0
      maxUnavailable: 1
    {{- end }}
  selector:
    matchLabels:
      app: dex-authenticator
      name: {{ $crd.name }}
  template:
    metadata:
      labels:
        app: dex-authenticator
        name: {{ $crd.name }}
      annotations:
        checksum/config: {{ $crd.credentials | toJson | b64enc | sha256sum }}
    spec:
{{- if $crd.spec.nodeSelector }}
      nodeSelector:
  {{- range $key, $value := $crd.spec.nodeSelector }}
        {{ $key | quote }}: {{ $value | quote }}
  {{- end }}
{{- else }}
      {{- include "helm_lib_node_selector" (tuple $context "system") | nindent 6 }}
{{- end }}
{{- if $crd.spec.tolerations }}
      tolerations: {{ $crd.spec.tolerations | toJson }}
{{- else }}
      {{- include "helm_lib_tolerations" (tuple $context "system") | nindent 6 }}
{{- end }}
      {{- include "helm_lib_priority_class" (tuple $context "cluster-low") | nindent 6 }}
      {{- include "helm_lib_pod_anti_affinity_for_ha" (list $context (dict "app" "dex-authenticator" "name" $crd.name)) | nindent 6 }}
      {{- include "helm_lib_module_pod_security_context_run_as_user_deckhouse" . | nindent 6 }}
      imagePullSecrets:
      - name: registry-dex-authenticator
      volumes:
      - name: tls
        emptyDir: {}
      initContainers:
      - args:
        - {{ $crd.name }}-dex-authenticator.{{ $crd.namespace }}
        - {{ $crd.name }}-dex-authenticator.{{ $crd.namespace }}.svc
        image: {{ include "helm_lib_module_image" (list $context "selfSignedGenerator") }}
        name: self-signed-generator
        volumeMounts:
        - name: tls
          mountPath: "/certs"
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 12 }}
        {{- include "helm_lib_module_container_security_context_read_only_root_filesystem_capabilities_drop_all" . | nindent 8 }}
      containers:
      - name: dex-authenticator
        {{- include "helm_lib_module_container_security_context_read_only_root_filesystem_capabilities_drop_all" . | nindent 8 }}
        image: {{ include "helm_lib_module_image" (list $context "dexAuthenticator") }}
        args:
        - --provider=oidc
        - --client-id={{ $crd.name }}-{{ $crd.namespace }}-dex-authenticator
    {{- if ne (include "helm_lib_module_uri_scheme" $context ) "https" }}
        - --cookie-secure=false
    {{- end }}
        - --redirect-url=https://{{ $crd.spec.applicationDomain }}
        - --oidc-issuer-url=https://{{ include "helm_lib_module_public_domain" (list $context "dex") }}/
        # Skip oidc issuer validation and discovery to avoid CrashLoopBackoffs
        - --skip-oidc-discovery
        - --redeem-url=https://dex.d8-user-authn/token
        - --login-url=https://{{ include "helm_lib_module_public_domain" (list $context "dex") }}/auth
        - --oidc-jwks-url=https://dex.d8-user-authn/keys
    {{- if $crd.spec.sendAuthorizationHeader }}
        - --set-authorization-header=true
    {{- end }}
        - --set-xauthrequest
        - --scope=groups email openid offline_access{{- if $crd.allowAccessToKubernetes }} audience:server:client_id:kubernetes{{- end }}
        - --ssl-insecure-skip-verify=true
        - --proxy-prefix=/dex-authenticator
        - --email-domain=*
        - --whitelist-domain={{ $crd.spec.applicationDomain }}
        - --upstream=file:///dev/null
        - --https-address=0.0.0.0:8443
        - --tls-cert-file=/opt/dex-authenticator/tls/tls.crt
        - --tls-key-file=/opt/dex-authenticator/tls/tls.key
        - --skip-provider-button
        - --silence-ping-logging
        - --session-store-type=redis
        - --redis-connection-url=redis://127.0.0.1/
        - --cookie-refresh={{ $context.Values.userAuthn.idTokenTTL | default "10m" }}
        - --cookie-expire={{ $crd.spec.keepUsersLoggedInFor | default "168h" }} # 7 days
        - --insecure-oidc-allow-unverified-email=true
        env:
        - name: OAUTH2_PROXY_CLIENT_SECRET
          valueFrom:
            secretKeyRef:
              name: dex-authenticator-{{ $crd.name }}
              key: client-secret
        - name: OAUTH2_PROXY_COOKIE_SECRET
          valueFrom:
            secretKeyRef:
              name: dex-authenticator-{{ $crd.name }}
              key: cookie-secret
        - name: TRUSTED_ROOT_CA_FILE
          value: /certs/ca.crt
        volumeMounts:
        - name: tls
          mountPath: "/opt/dex-authenticator/tls"
          readOnly: true
        readinessProbe:
          exec:
            command:
            - /url-exec-prober
            - https://dex.d8-user-authn/.well-known/openid-configuration
          initialDelaySeconds: 5
          periodSeconds: 5
          failureThreshold: 5
        livenessProbe:
          httpGet:
            port: 8443
            scheme: HTTPS
            path: /ping
          initialDelaySeconds: 15
          periodSeconds: 10
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_logs_with_extra" 10 | nindent 12 }}
  {{- if not ($context.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
            {{- include "dex_authenticator_resources" . | nindent 12 }}
  {{- end }}
        ports:
        - containerPort: 8443
          protocol: TCP
      - name: redis
        {{- include "helm_lib_module_container_security_context_read_only_root_filesystem_capabilities_drop_all" . | nindent 8 }}
        image: {{ include "helm_lib_module_common_image" (list $context "redisStatic") }}
        args:
          - "--save"
          - ""
          - "--appendonly"
          - "no"
          - "--bind"
          - "127.0.0.1"
        resources:
          requests:
            {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 12 }}
  {{- if not ($context.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
            {{- include "redis_resources" . | nindent 12 }}
  {{- end }}
{{- end }}
